import { Component } from "react";
import './Item.css'

export class Item extends Component {
    state = {
        mouseCovered: false
    }
    // 控制鼠标移入移出效果
    handleMouseLeave = (isLeave) =>
        isLeave ? () => {
            this.setState({
                mouseCovered: false
            })
        } : () => {
            this.setState({
                mouseCovered: true
            })
        }
    
    // 删除待办
    handleRemoveTodoItem = (id) => {
        const {removeTodoItem} = this.props
        return () => {
            if(window.confirm('确定要删除吗？')){
                console.log(id)
                removeTodoItem(id)
            }
        }
    }

    // 处理勾选框勾选变动
    handleCheckBoxChanged = (id) => {
        const {checkBoxChanged} = this.props
        return (event) => {
            checkBoxChanged(id, event.target.checked)
        }
    }

    render() {
        const { mouseCovered } = this.state
        const {id, title, completed } = this.props
        return (
            <li className={mouseCovered ? 'active' : ''} onMouseOver={this.handleMouseLeave(false)} onMouseLeave={this.handleMouseLeave(true)}>
                <label>
                    {/* defaultChecked 默认选中状态 */}
                    <input type="checkbox" checked={completed} onChange={this.handleCheckBoxChanged(id)}/>
                    <span>{title}</span>
                </label>
                <button className="btn btn-danger" style={{ display: mouseCovered ? 'block' : 'none' }} onClick={this.handleRemoveTodoItem(id)}>删除</button>
            </li>
        )
    }
}